﻿using QQZiFramework;
using QQZiFramework.Modals;
using System;
using System.Collections.Generic;
using System.DrawingCore;
using System.DrawingCore.Drawing2D;
using System.DrawingCore.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using QQZiFramework.Membership;
using System.Collections;
using QRCoder;
using System.IO;
using System.Collections.Specialized;
using System.Xml;

namespace QQZiFramework
{
    public class Utility
    {
        /// <summary>
        /// 转换为int值，如果非数值类型，则为0
        /// </summary>
        /// <param name="numberObj"></param>
        /// <returns></returns>
        public static int ToInt32(object numberObj)
        {
            int value;
            int.TryParse(numberObj.ToString(), out value);
            return value;
        }
        /// <summary>
        /// int值，如果非数值类型，则为nullValue
        /// </summary>
        /// <param name="numberObj"></param>
        /// <param name="nullValue"></param>
        /// <returns></returns>
        public static int ToInt32(object numberObj, int nullValue)
        {
            int value;
            if (!int.TryParse(numberObj.ToString(), out value)) value = nullValue;
            return value;
        }


        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <param name="urlDecode">是否使用地址栏编辑，web传上来的时候为true</param>
        /// <returns>解密后的字符串</returns>

        public static string DecodeBase64(string result, bool urlDecode)
        {
            byte[] bytes = Convert.FromBase64String(result);
            string str = Encoding.UTF8.GetString(bytes);
            if (urlDecode) return System.Web.HttpUtility.UrlDecode(str);
            else return str;
        }

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="str">要加密的内容</param>
        /// <param name="urlDecode">是否要地址栏编辑，Web传值的时候为True</param>
        /// <returns>密文</returns>
        public static string EncodeBase64(string str, bool urlDecode)
        {
            if (urlDecode) str = System.Web.HttpUtility.UrlEncode(str);
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        {
            return DecodeBase64(result, false);
        }

        public static string ToParamString(NameValueCollection nvc)
        {
            string strEncrypt = "";
            foreach (string key in nvc.Keys)
            {
                strEncrypt += "&" + key + "=" + System.Net.WebUtility.UrlEncode(nvc[key]);
            }
            if (strEncrypt.Length > 0) return strEncrypt.Substring(1);
            else return strEncrypt;
        }

        static EncryptionUtility encryption = new EncryptionUtility("TfoPqado2GvjxvC1GsmY6Q==");

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Encrypt(string str)
        {
            byte[] bs = encryption.EncryptData(str);
            return Convert.ToBase64String(bs);
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="urlEncode">是否要进行urlencode</param>
        /// <returns></returns>
        public static string Encrypt(string str, bool urlEncode)
        {
            byte[] bs = encryption.EncryptData(str);
            if (urlEncode) return System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(bs));
            else return Convert.ToBase64String(bs);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Decrypt(string str)
        {
            if (string.IsNullOrEmpty(str)) return str;
            byte[] bs64str = Convert.FromBase64String(str);
            return encryption.DecryptData(bs64str);
        }


        /// <summary>
        /// 加密数字
        /// </summary>
        /// <param name="add">是否再加上一个数字来打乱</param>
        /// <returns></returns>
        public static string EncryptNumber(int number, bool add = true)
        {
            double d = 0;
            if (add)
            {
                string str = number.ToString();//取最后一位数+1拿来混合
                int last = Convert.ToInt32(str[str.Length - 1].ToString()) + 1;
                d = (double)number * last + 10086;
                return ConvertToInt26(d) + ConvertToInt26(last);
            }
            else
            {
                d = (double)number;
                return ConvertToInt26(d);
            }
        }

        /// <summary> 
        /// 字符串转16进制字节数组 
        /// </summary> 
        public static byte[] HexToByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary> 
        /// 字符串转16进制字符 
        /// </summary> 
        public static string HexToStr(string hexString)
        {
            return Encoding.UTF8.GetString(HexToByte(hexString));
        }

        /// <summary> 
        /// 转16进制字符串 
        /// </summary>
        public static string ToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 转16进制字符串 
        /// </summary>
        public static string ToHexStr(string str)
        {
            return ToHexStr(Encoding.UTF8.GetBytes(str));
        }

        /// <summary>
        /// 获取加*号的名字
        /// </summary>
        /// <returns></returns>
        public static string EncryptName(string name)
        {
            if (name == null || name.Length < 2) return name;
            string sss = name[0].ToString();
            for (int i = 1; i < name.Length - 1; i++)
            {
                sss += "*";
            }
            if (name.Length > 2) sss += name[name.Length - 1].ToString();
            return sss;
        }

        /// <summary>
        /// 获取加*号的手机
        /// </summary>
        /// <returns></returns>
        public static string EncryptMobile(string mobile)
        {
            if (string.IsNullOrEmpty(mobile)) return mobile;
            return mobile.Substring(0, 3) + "****" + mobile.Substring(7, 4);

        }

        /// <summary>
        /// int转26进制字符串
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string ConvertToInt26(double number)
        {
            string s = string.Empty;
            while (number > 0)
            {
                double m = number % 26;
                if (m == 0) m = 26;
                s = (char)(m + 64) + s;
                number = (number - m) / 26;
            }
            return s;
        }

        public static string Code26Add(string code26Str, int diff)
        {
            int substringLen = 5;
            if (code26Str.Length < substringLen) substringLen = code26Str.Length;
            string str2 = code26Str.Substring(code26Str.Length - substringLen);
            str2 = ConvertToInt26(ConvertFormInt26(str2) + diff);
            string result = code26Str.Substring(0, code26Str.Length - substringLen) + str2;
            return result;
        }

        /// <summary>
        /// 26进制字符串转Int
        /// </summary>
        /// <param name="numberStr"></param>
        /// <returns></returns>
        public static double ConvertFormInt26(string numberStr)
        {
            if (string.IsNullOrEmpty(numberStr)) return 0;
            double n = 0, j = 1;
            for (int i = numberStr.Length - 1; i >= 0; i--, j *= 26)
            {
                char c = Char.ToUpper(numberStr[i]);
                if (c < 'A' || c > 'Z')
                {
                    if (c == '0') c = 'A';
                    else return 0;
                }
                n += ((int)c - 64) * j;
            }
            return n;
        }

        /// <summary>
        /// 解密数字
        /// </summary>
        /// <param name="add">密文是否有加数值打乱</param>
        /// <returns></returns>
        public static int DecryptNumber(string numberStr, bool add = true)
        {
            double lastInt = 0;
            if (add)
            {
                char last = numberStr[numberStr.Length - 1];
                lastInt = ConvertFormInt26(last.ToString());
                numberStr = numberStr.Substring(0, numberStr.Length - 1);
            }
            double n = ConvertFormInt26(numberStr);
            if (add)
            {
                n = (n - 10086) / lastInt;
            }
            return (int)n;
        }

        public static string SHA1Encrypt(string intput)
        {
            byte[] StrRes = Encoding.Default.GetBytes(intput);
            HashAlgorithm mySHA = new SHA1CryptoServiceProvider();
            StrRes = mySHA.ComputeHash(StrRes);
            StringBuilder EnText = new StringBuilder();
            foreach (byte Byte in StrRes)
            {
                EnText.AppendFormat("{0:x2}", Byte);
            }
            return EnText.ToString();
        }

        /// <summary>
        /// 用MD5方式加密字符串
        /// </summary>
        /// <param name="strPassword"></param>
        /// <returns></returns>
        public static string EncryptMD5(string strPassword)
        {
            MD5 objMD5 = new MD5CryptoServiceProvider();
            byte[] arrRndHashPwd = objMD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strPassword));
            string strRndHashPwd = "";
            foreach (byte b in arrRndHashPwd)
            {
                if (b < 16)
                    strRndHashPwd = strRndHashPwd + "0" + b.ToString("X");
                else
                    strRndHashPwd = strRndHashPwd + b.ToString("X");
            }
            return strRndHashPwd;
        }

        public static string EncryptMD5_QQZI(string strPassword)
        {
            MD5 objMD5 = new MD5CryptoServiceProvider();
            byte[] arrRndHashPwd = objMD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strPassword));
            string strRndHashPwd = "";
            foreach (byte b in arrRndHashPwd)
            {
                if (b < 16)
                    strRndHashPwd = strRndHashPwd + "0" + b.ToString("X");
                else
                    strRndHashPwd = strRndHashPwd + b.ToString("X");
            }
            return strRndHashPwd.Substring(5, 20);
        }


        /// <summary>
        /// 将颜色额转换成由16进制RGB分量表示的字符串。
        /// 例如：红色-#FF0000
        /// </summary>
        /// <param name="color">颜色</param>
        /// <returns>返回颜色字符串</returns>
        public static string GetColorString(Color color)
        {
            return string.Format("#{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B);
        }
        /// <summary>
        /// 微信的基准时间
        /// </summary>
        private static readonly DateTime baseTime = new DateTime(1970, 1, 1);

        /// <summary>
        /// 返回微信时间（距1970年1月1日0点的秒数）
        /// </summary>
        /// <param name="dt">时间</param>
        /// <returns>返回微信时间</returns>
        public static int ToWeixinTime(DateTime dt)
        {
            return (int)(dt - baseTime).TotalSeconds;
        }
        /// <summary>
        /// 将微信服务器返回的表示日期时间的秒数，转换成日期时间。
        /// 秒数的计时起点为1970年1月1日0点。
        /// 注：微信采用UTC时间，需要转换成本地时间。
        /// </summary>
        /// <param name="seconds">秒数</param>
        /// <returns>返回日期时间</returns>
        [Obsolete("请使用ToDateTime(Int64 seconds)")]
        public static DateTime ToDateTime(int seconds)
        {
            return TimeZoneInfo.ConvertTimeFromUtc(baseTime.AddSeconds(seconds), TimeZoneInfo.Local);
        }

        /// <summary>
        /// 时间戳（秒）转Datetime
        /// </summary>
        /// <param name="seconds">秒数</param>
        /// <returns>返回日期时间</returns>
        public static DateTime ToDateTime(Int64 seconds)
        {
            return TimeZoneInfo.ConvertTimeFromUtc(baseTime.AddSeconds(seconds), TimeZoneInfo.Local);
        }

        /// <summary>
        /// 时间戳（毫秒）转Datetime
        /// </summary>
        /// <param name="milliseconds">毫秒数</param>
        /// <returns>返回日期时间</returns>
        public static DateTime ToDateTimeFromMillise(Int64 milliseconds)
        {
            return TimeZoneInfo.ConvertTimeFromUtc(baseTime.AddMilliseconds(milliseconds), TimeZoneInfo.Local);
        }


        /// <summary>
        /// 获取字符串两端的数据
        /// </summary>
        /// <param name="all"></param>
        /// <param name="leftString"></param>
        /// <param name="rightString"></param>
        /// <param name="include"></param>
        /// <returns></returns>
        public static string bothside(string all, string leftString, string rightString, bool include = false, string replace = "", bool min = false)
        {
            //     Console.WriteLine("搜索字符串all,找到all中,从left,到right去除中间的字符串");       
            int leftNum = all.IndexOf(leftString);
            int rightNum = all.IndexOf(rightString, leftNum + leftString.Length + 1);
            //     Console.WriteLine(" leftNum:" + leftNum + " \n rightNum:" + rightNum + " \n leftString.Length:" + leftString.Length + "\n");
            if (leftNum != -1 && rightNum != -1 && (leftNum + leftString.Length) < rightNum)
            {
                if (min == true)
                {
                    int minleftNum = leftNum;
                    while (minleftNum < rightNum && minleftNum != -1)
                    {
                        minleftNum = all.IndexOf(leftString, minleftNum + 1);
                        if (minleftNum != -1)
                        {
                            leftNum = minleftNum;
                        }
                    }
                }
                string bothSideText = "";
                if (include == true)
                {
                    //            Console.WriteLine("左边的长度+右边的长度");
                    bothSideText = all.Substring(0, leftNum + leftString.Length) + replace + all.Substring(rightNum);
                }
                else
                {
                    bothSideText = all.Substring(0, leftNum) + replace + all.Substring(rightNum + rightString.Length);
                }

                //  Console.WriteLine(bothSideText);
                //          Thread.Sleep(10000);    //暂停1秒

                return bothSideText;
            }

            else return "错误字符串不存在或重合或位置重合";


        }

        /// <summary>
        /// 获取字符串中间的数据
        /// </summary> 
        /// <param name="all"></param>
        /// <param name="leftString"></param>
        /// <param name="rightString"></param>
        /// <param name="include"></param>
        /// <returns></returns>
        public static string getMiddle(string all, string leftString, string rightString, bool include = false, bool min = false)
        {
            //Console.WriteLine("搜索字符串all,找到all中,从left,到right中间的字符串");
            if (string.IsNullOrEmpty(all)) return null;
            int leftNum = all.IndexOf(leftString);
            int rightNum = all.IndexOf(rightString, leftNum + leftString.Length);
            if (leftNum == rightNum) return string.Empty;
            if (rightNum == -1) rightNum = all.Length;
            // Console.WriteLine("左边字符串和右边字符串必须存在，且不能位置重合,可以存在保存或者删除左右两边字符串");
            // Console.WriteLine(" leftNum:" + leftNum + " \n rightNum:" + rightNum + " \n leftString.Length:" + leftString.Length + "\n");
            if (leftNum != -1 && rightNum != -1 && (leftNum + leftString.Length) < rightNum)
            {
                if (min == true)
                {
                    int minleftNum = leftNum;
                    while (minleftNum < rightNum && minleftNum != -1)
                    {
                        minleftNum = all.IndexOf(leftString, minleftNum);
                        if (minleftNum != -1)
                        {
                            leftNum = minleftNum;
                        }
                    }
                }
                string MiddleText = "";
                if (include == true)
                {
                    //Console.WriteLine("从字符串左边开始,包括左右边两边字符串");
                    MiddleText = all.Substring(leftNum, rightNum - leftNum + rightString.Length);

                }
                else
                {
                    // Console.WriteLine("从字符串左边开始,不包括左右边字符串的长度");
                    MiddleText = all.Substring(leftNum + leftString.Length, rightNum - (leftNum + leftString.Length));
                }
                // Console.WriteLine(MiddleText);
                // Thread.Sleep(10000);    //暂停1秒
                return MiddleText;
            }
            else return null;


        }

        /// <summary>
        /// 判断是否数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNumeric(string value)
        {
            return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
        }

        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>400
        /// <param name="dWidth"></param>400
        /// <param name="flag">压缩质量 1-100</param>50
        /// <returns></returns>

        public static byte[] GetPicThumbnail(byte[] fileBytes, int dHeight, int dWidth, int flag)
        {
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(fileBytes);
            System.DrawingCore.Image iSource = System.DrawingCore.Image.FromStream(memoryStream);
            memoryStream.Close();
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
            {

                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }

                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);

            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);

            g.CompositingQuality = CompositingQuality.HighQuality;

            g.SmoothingMode = SmoothingMode.HighQuality;

            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.DrawingCore.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {

                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();

                ImageCodecInfo jpegICIinfo = null;

                for (int x = 0; x < arrayICI.Length; x++)
                {

                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {

                        jpegICIinfo = arrayICI[x];

                        break;

                    }

                }
                memoryStream = new System.IO.MemoryStream();
                if (jpegICIinfo != null)
                {
                    ob.Save(memoryStream, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(memoryStream, tFormat);
                }
                iSource.Dispose();
                ob.Dispose();
                return memoryStream.ToArray();

            }

            catch (Exception ex)
            {
                iSource.Dispose();
                ob.Dispose();
                throw ex;
            }
        }
        static int ExtraOrder_orderLen = 16;
        static int ExtraOrder_totalLen = 24;

        /// <summary>
        /// 生成不重复的订单号（汇付用），前9位为我们的orderId
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public static string GetExtraOrderId(string orderId)
        {
            string ExtraOrderId = orderId;
            string time = DateTime.Now.Ticks.ToString();
            //  int num = 7 - ExtraOrderId.Length;
            //   ExtraOrderId = ExtraOrderId + time.Substring(time.Length - num );
            for (int num = ExtraOrderId.Length; num < ExtraOrder_orderLen; num++)
            {
                ExtraOrderId = "0" + ExtraOrderId;
            }
            ExtraOrderId = ExtraOrderId + time.Substring(time.Length - (ExtraOrder_totalLen - ExtraOrder_orderLen));

            return ExtraOrderId;
        }
        /// <summary>
        /// 转换汇付的订单为我们的OrderId
        /// </summary>
        /// <param name="extraOrderId"></param>
        /// <returns></returns>
        public static Int64 GetFromExtraOrder(string extraOrderId)
        {
            if (extraOrderId.Length < 10) return Convert.ToInt64(extraOrderId);
            else if (extraOrderId.Length < 24)
            {
                //兼容之前
                return Convert.ToInt64(extraOrderId.Substring(0, 9));
            }
            else
            {
                return Convert.ToInt64(extraOrderId.Substring(0, ExtraOrder_orderLen));
            }

        }

        /// <summary>
        /// 获取Source对象某个属性的值
        /// </summary>
        public static object GetSourcePropertyValue(string name, object args)
        {
            if (args == null) throw new ArgumentNullException("args");
            if (args is IDictionary)
            {
                //hashtable
                return ((IDictionary)args)[name];
            }
            else if (args is IDictionary<string, object>)
            {
                //兼容object字典类型
                return ((IDictionary<string, object>)args)[name];
            }
            else if (args is IDictionary<string, string>)
            {
                //兼容string字典类型
                return ((IDictionary<string, string>)args)[name];
            }
            if (args is Newtonsoft.Json.Linq.JToken)
            {
                string value = null;
                ((Newtonsoft.Json.Linq.JToken)args).TryGetValue<string>(name.Replace('.', ':'), out value);
                return value;
            }
            object o = null;
            foreach (string pname in name.Split('.'))
            {
                System.Reflection.PropertyInfo propertyInfo = args.GetType().GetProperty(pname);
                if (propertyInfo == null) throw new Exception(name + "属性不存在");
                o = propertyInfo.GetValue(args);
                if (o == null) throw new Exception(name + "属性不能为空");
                args = o;

            }
            return o;
        }

        /// <summary>
        /// 用来格式化大括号包起来的模板
        /// </summary>
        /// <param name="dataSource">数据源，支付类和字典</param>
        public static string FormatTemplate(string template, object dataSource)
        {

            int left = template.IndexOf("{");
            int right = template.IndexOf("}");
            StringBuilder str = new StringBuilder();
            while (left >= 0 && right >= 0)
            {

                //得到标签名称
                string label = template.Substring(left + 1, right - left - 1);
                if (label[0] < 48 || label[0] > 57)//非数字 {0}
                {
                    //标签前面内容直接输出
                    str.Append(template.Substring(0, left));
                    object val = GetSourcePropertyValue(label, dataSource);
                    if (val != null) str.Append(val.ToString());
                    else str.Append("{" + label + "}");
                }
                else
                {
                    //标签前面内容直接输出
                    str.Append(template.Substring(0, right + 1));
                }
                //模板中已生成的内容截取掉
                template = template.Substring(right + 1);
                //重新设置第一个标签的开始和结束0                 
                left = template.IndexOf("{");
                right = template.IndexOf("}");
            }
            if (template.Length > 0) str.Append(template);
            return str.ToString();
        }

        /// <summary>
        /// 正则匹配多个
        /// </summary>
        /// <param name="strHtmlCode">网页源码</param>
        public static ArrayList GetList(string strHtmlCode, string pattern)
        {
            ArrayList al = new ArrayList();
            string htmlCode = strHtmlCode;
            // string pattern = "<a href=\"guahao/guahaoqr\\.php\\?id=(.*?)\">[\\s\\S]*?<div class=\"block12a\">[\\s\\S]*?<div class=\"block12d\">(.*?)</div>[\\s\\S]*?<div class=\"block12d\"><p>(.*?)</p><span>[\\s\\S]*?<font class=\"green font48\">(.*?)</font></span>[\\s\\S]*?</div>[\\s\\S]*?</div>[\\s\\S]*?</a>";
            Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection m = r.Matches(htmlCode);
            for (int i = 0; i <= m.Count - 1; i++)
            {
                string strNew = m[i].ToString();
                Regex l = new Regex(pattern, RegexOptions.None);
                Match mc = l.Match(strNew);
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < mc.Groups.Count - 1; j++)
                {
                    sb.Append(mc.Groups[j + 1].Value);
                    sb.Append("|");
                }
                al.Add(sb.ToString().Trim('|'));
            }
            return al;
        }

        /// <summary>
        /// 正则匹配一个内容
        /// </summary>
        /// <param name="result">源</param>
        /// <param name="pattern">表达式</param>
        /// <returns>匹配值</returns>
        public static string RegexOneValues(string result, string pattern)
        {
            if (result == null) return "";
            if (result == "") return "";
            if (string.IsNullOrEmpty(result)) return "";
            Regex reg = new Regex(pattern);
            Match match = reg.Match(result);
            return match.Groups[1].Value;
        }

        /// <summary>  
        /// 单个数字转为大写  
        /// </summary>  
        /// <param name="c">小写阿拉伯数字 0---9</param>  
        /// <returns>大写数字</returns>  
        public static string Getint(char c)
        {
            string str = "";
            switch (c)
            {
                case '0':
                    str = "零";
                    break;
                case '1':
                    str = "壹";
                    break;
                case '2':
                    str = "贰";
                    break;
                case '3':
                    str = "叁";
                    break;
                case '4':
                    str = "肆";
                    break;
                case '5':
                    str = "伍";
                    break;
                case '6':
                    str = "陆";
                    break;
                case '7':
                    str = "柒";
                    break;
                case '8':
                    str = "拐";
                    break;
                case '9':
                    str = "玖";
                    break;
            }
            return str;
        }

        /// <summary>
        /// 数写字符串转大写
        /// </summary>
        /// <param name="str">0123-->零一二三</param>
        /// <returns></returns>
        public static string NmberToCn(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char item in str)
            {
                sb.Append(Getint(item));
            }
            return sb.ToString();
        }


        // /// <summary>
        // /// 获取Webconfig中appsetting的值
        // /// </summary>
        // /// <typeparam name="T"></typeparam>
        // /// <param name="name"></param>
        // /// <returns></returns>
        // public static T GetAppSetting<T>(string name, char end = ' ')
        // {
        //     string str = System.Configuration.ConfigurationManager.AppSettings[name];
        //     if (str == null) throw new ClientException(name + "没有配置在appsetting中");
        //     if (str == String.Empty) return default(T);
        //     if (end != ' ')
        //     {
        //         if (str[str.Length - 1] != end) str = str + end;
        //     }
        //     return (T)Convert.ChangeType(str, typeof(T));

        // }

        static Regex sql_regex = new Regex("\\b(\\s*and\\s*|\\s*in\\s*|\\s*exec\\s*|\\s*insert\\s*|\\s*select\\s*|\\s*from\\s*|\\s*union\\s*|\\s*drop\\s*|\\s*grant\\s*|\\s*alter\\s*|\\s*delete\\s*|\\s*update\\s*|\\s*truncate\\s*|\\s*declare\\s*|\\s*or\\s*)\\b");

        /// <summary>
        /// 检测sql注入
        /// </summary>
        /// <param name="val"></param>
        /// <param name="throwWhen"></param>
        /// <returns></returns>
        public static bool CheckSqlXSS(string val, bool throwWhen = true)
        {
            bool has = sql_regex.IsMatch(val);
            if (has && throwWhen) throw new ClientException("存在入侵嫌疑!");
            return has;
        }

        /// <summary>
        /// 去除script之间的内容
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoeScriptTag(ref string content)
        {
            string scripts = "";
            int startPos = content.IndexOf("<script", StringComparison.OrdinalIgnoreCase);
            while (startPos > -1)
            {
                int endPos = content.IndexOf("</script>", startPos + 6, StringComparison.OrdinalIgnoreCase);
                if (endPos > -1)
                {
                    //找到<script的结束>，因为有可能有其实属性，比如 src
                    int findLength = endPos - startPos;
                    if (findLength > 150) findLength = 150;
                    var startPos2 = content.IndexOf('>', startPos, findLength);
                    if (startPos2 > -1 && endPos - startPos2 > 3) scripts += content.Substring(startPos2 + 7, endPos - startPos2 - 8);
                    content = content.Remove(startPos, endPos - startPos + 9);
                    startPos = content.IndexOf("<script", startPos);
                }
                else break;
            }
            return scripts;

        }


        protected static long lLeft = 621355968000000000;

        /// <summary>
        /// 时间戳（毫秒）
        /// </summary>
        public static long GetIntFromTime()
        {
            DateTime dt = DateTime.Now;
            long Sticks = (dt.ToUniversalTime().Ticks - 621355968000000000) / 10000;
            return Sticks;

        }

        /// <summary>
        /// 时间戳（毫秒）
        /// </summary>
        public static long GetIntFromTime(DateTime dt)
        {
            long Sticks = (dt.ToUniversalTime().Ticks - 621355968000000000) / 10000;
            return Sticks;

        }


        public static byte[] QREncode(string contentStr)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(contentStr, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(20);
            System.IO.MemoryStream stream = new MemoryStream();
            qrCodeImage.Save(stream, ImageFormat.Jpeg);
            byte[] bytes = stream.ToArray();
            stream.Close();
            return bytes;
        }
        public static string QRDecode(string imgPath)
        {
            // ThoughtWorks.QRCode.Codec.QRCodeDecoder decoder = new ThoughtWorks.QRCode.Codec.QRCodeDecoder();
            // return decoder.decode(new ThoughtWorks.QRCode.Codec.Data.QRCodeBitmapImage(new System.Drawing.Bitmap(System.Drawing.Image.FromFile(imgPath))));

            Image image = Image.FromFile(imgPath);
            ZXing.ZKWeb.BarcodeReader qRCodeReader = new ZXing.ZKWeb.BarcodeReader();
            qRCodeReader.Options = new ZXing.Common.DecodingOptions
            {
                CharacterSet = "UTF-8"
            };
            Bitmap bitmap = new Bitmap(image);
            string str = qRCodeReader.Decode(bitmap).Text;
            bitmap.Dispose();
            image.Dispose();
            return str;
        }




        /// <summary>
        /// 创建图片验证码
        /// </summary>
        public static byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线


                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 11, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }


        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="length">指定验证码的长度</param>
        /// <returns></returns>
        public static string CreateValidateCode(int length)
        {

            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,O,P,Q,R,S,T,U,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,s,t,u,w,x,y,z";
            string[] allCharArray = allChar.Split(',');//拆分成数组
            string randomNum = "";
            int temp = -1;                             //记录上次随机数的数值，尽量避免产生几个相同的随机数
            Random rand = new Random();
            for (int i = 0; i < length; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                //if (temp == t)
                //{
                //    return CreateValidateCode(length);
                //}
                //temp = t;
                randomNum += allCharArray[t];
            }
            return randomNum;
        }
        /// <summary>
        /// XMl报文转为哈希列表
        /// </summary>
        /// <param name="content">XML内容</param>
        public static Hashtable XMLToHast(string content)
        {
            Hashtable hash = new Hashtable();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(content);
            XmlNode root = xmlDoc.SelectSingleNode("xml");
            XmlNodeList xnl = root.ChildNodes;
            foreach (XmlNode xnf in xnl)
            {
                if (xnf.Name != null && xnf.Name != "")
                {
                    hash.Add(xnf.Name, xnf.InnerText);
                }
            }
            return hash;
        }


        public static string ReadFile(string file)
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);
            if (!fileInfo.Exists) throw new System.IO.FileNotFoundException(file);
            try
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(file, Encoding.UTF8);
                string str = reader.ReadToEnd();
                reader.Close();
                return str;
            }
            catch (Exception ex)
            {
                throw new ClientException("读取文件出错" + ex.Message);
            }

        }

    }
}
